package com.jarchie.androiddev.ui.views

import android.annotation.SuppressLint
import android.content.Context
import android.text.TextUtils
import android.util.AttributeSet
import android.view.Gravity
import android.view.LayoutInflater
import android.widget.LinearLayout
import androidx.annotation.DrawableRes
import com.jarchie.androiddev.databinding.LayoutLoadingStatusViewBinding

class LoadingStatusView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
    LinearLayout(context, attrs, defStyleAttr) {
    private val binding =
        LayoutLoadingStatusViewBinding.inflate(LayoutInflater.from(context), this, true)

    init {
        orientation = VERTICAL
        gravity = Gravity.CENTER
        binding.loading.show()
    }

    @SuppressLint("ResourceType")
    fun showEmpty(@DrawableRes iconRes: Int = 0, text: String? = null, retry: OnClickListener?) {
        binding.loading.hide()
        binding.emptyLayout.visibility = VISIBLE
        if (iconRes > 0) {
            binding.emptyIcon.setImageResource(iconRes)
        }
        if (!TextUtils.isEmpty(text)) {
            binding.emptyText.setText(text)
        }
        retry?.run {
            binding.emptyAction.setOnClickListener(this)
        }
    }

    override fun setVisibility(visibility: Int) {
        super.setVisibility(visibility)
        if (visibility != VISIBLE) {
            binding.loading.hide()
        }
    }
}